package com.simple.datax.conn.impl;


import org.apache.commons.pool.BaseKeyedPoolableObjectFactory;

import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import com.simple.datax.api.ConnectorException;
import com.simple.datax.conn.BaseConnector;

/** 
 * @Title: ConnectorFactory.java 
 * @Package com.simple.datax.conn.impl 
 * @Description: 实现连接工厂
 * @author Joe Jin
 * @date 2012-12-26
 * @version V1.0 
 */
public class ConnectorFactory extends BaseKeyedPoolableObjectFactory<String, BaseConnector> {
	private static final Logger logger = LoggerFactory
			.getLogger(ConnectorFactory.class);
	public static final String KEY_SPLITTER = ":";
	private static ConnectorFactory factory = null;
	
	private ConnectorFactory() {
		
	}
	
	/**
	 * Singleton
	 * @return
	 */
	public static synchronized ConnectorFactory getInstance() {
		if (factory == null) {
			factory = new ConnectorFactory();
		}
		return factory;
	}
	
	@Override
	public BaseConnector makeObject(String key) throws Exception {
		BaseConnector connector = null;
		if (key != null && !key.isEmpty()) {
			int pos = key.indexOf(KEY_SPLITTER);
			//logger.debug("connector Splitter pos:" + pos);
			if (pos > 0) {
				String connType = key.substring(0, pos);
				if (connType != null) {
					connType = connType.trim();					
				}
				//logger.debug("connectot connType:" + connType);
				String connPara = key.substring(pos+1);
				
				if (FTPConnImpl.TYPE.equalsIgnoreCase(connType)) { //FTP or FTPS
					connector = new FTPConnImpl(connPara);
				} else if ((FTPConnImpl.TYPE+"S").equalsIgnoreCase(connType)) { //FTP or FTPS
					connector = new FTPConnImpl(connPara, true);
				} else if (ActiveMQConnImpl.TYPE.equalsIgnoreCase(connType)) { //ActiveMQ
					connector = new ActiveMQConnImpl(connPara);
				} else if (IBMMQConnImpl.TYPE.equalsIgnoreCase(connType)) { //IBMMQ
					connector = new IBMMQConnImpl(connPara);
				} else if (MSMQConnImpl.TYPE.equalsIgnoreCase(connType)) { //MSMQ
					connector = new MSMQConnImpl(connPara);
				} else if (HornetqConnImpl.TYPE.equalsIgnoreCase(connType)) { //HornetQ
					connector = new HornetqConnImpl(connPara);
				} else if (LocalFileConnImpl.TYPE.equalsIgnoreCase(connType)) { //Local File
					connector = new LocalFileConnImpl(connPara);
				} else if (SFTPConnImpl.TYPE.equalsIgnoreCase(connType)) { //SFTP
					connector = new SFTPConnImpl(connPara);
				} else {
					logger.error("Unsupported connector type - " + connType);
					throw new ConnectorException("Unsupported connector type - " + connType);
				}
			}
		}
		return connector;
	}
}
